package com.ht.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.modules.system.entity.SysRole;
import com.ht.modules.system.entity.SysUser;
import com.ht.modules.system.entity.SysUserRole;
import com.ht.modules.system.mapper.SysUserRoleMapper;
import com.ht.modules.system.service.ISysRoleService;
import com.ht.modules.system.service.ISysUserRoleService;
import com.ht.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户角色表 服务实现类
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

	@Autowired
	private ISysUserService userService;
	@Autowired
	private ISysRoleService roleService;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	/**
	 * 查询所有用户对应的角色信息
	 */
	@Override
	public Map<String,String> queryUserRole() {
		List<SysUserRole> uRoleList = this.list();
		List<SysUser> userList = userService.list();
		List<SysRole> roleList = roleService.list();
        Map<String,String> roleMap = roleList.stream().collect(Collectors.toMap(SysRole::getId, SysRole::getRoleName));
		Map<String,String> map = new IdentityHashMap<>();
		String userId;
		String roleId;
		String roleName;
		if(uRoleList != null && !uRoleList.isEmpty()) {
			for(SysUserRole uRole : uRoleList) {
				roleId = uRole.getRoleId();
				for(SysUser user : userList) {
					userId = user.getId();
					if(uRole.getUserId().equals(userId)) {
                        roleName = roleMap.get(roleId);
						map.put(userId, roleName);
					}
				}
			}
			return map;
		}
		return map;
	}

	@Override
	public List<String> queryRoleCodeByUserId(String id) {
		return sysUserRoleMapper.getRoleCodeByUserId(id);
	}

	@Override
	public String getRoleIdByUserId(String userId) {
		return sysUserRoleMapper.getRoleIdByUserId(userId);
	}

}
